package com.ruihu.admin.module.business.tasknode.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ruihu.admin.common.constant.JudgeEnum;
import com.ruihu.admin.common.domain.ResponseDTO;
import com.ruihu.admin.common.domain.RetDTO;
import com.ruihu.admin.constant.CommonConst;
import com.ruihu.admin.module.business.log.interfacelog.constant.InterfaceModuleEnum;
import com.ruihu.admin.module.business.log.interfacelog.dao.ElectricUpdateMessageQueueDao;
import com.ruihu.admin.module.business.log.interfacelog.dao.InterfaceLogDao;
import com.ruihu.admin.module.business.log.interfacelog.domain.dto.ElectricUpdateMessageQueueQueryDTO;
import com.ruihu.admin.module.business.log.interfacelog.domain.dto.InterfaceLogQueryDTO;
import com.ruihu.admin.module.business.log.interfacelog.domain.entity.ElectricUpdateMessageQueueEntity;
import com.ruihu.admin.module.business.log.interfacelog.domain.entity.InterfaceLogEntity;
import com.ruihu.admin.module.business.task.constant.TaskResponseCodeConst;
import com.ruihu.admin.module.business.task.domain.entity.SubTaskEntity;
import com.ruihu.admin.module.business.tasknode.manager.InterfaceManager;
import com.ruihu.admin.module.support.task.service.AIImageDyTask;
import com.ruihu.admin.module.support.task.service.DyTaskService;
import com.ruihu.admin.module.system.systemconfig.SystemConfigService;
import com.ruihu.admin.module.system.systemconfig.constant.SystemConfigEnum;
import com.ruihu.admin.module.system.systemconfig.domain.dto.SystemConfigDTO;
import com.ruihu.admin.util.RequestTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * AI接口
 */
@Service
@Slf4j
public class AIInterfaceService {

    private static final String DEFAULT_CRON_EXPRESSION = "0/5 * * * * ?";

    @Value("${ai.interface.jizu.url}")
    private String aiInterfaceJzUrl;

    @Autowired
    private DyTaskService dyTaskService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private InterfaceLogDao interfaceLogDao;

    @Autowired
    private ElectricUpdateMessageQueueDao electricUpdateMessageQueueDao;

    @Autowired
    private InterfaceManager interfaceManager;

    /**
     * 发送电芯新增编码消息
     * @param subTaskEntity
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendElectricCoreAddMessage(SubTaskEntity subTaskEntity) {
        ElectricUpdateMessageQueueQueryDTO queryDTO = new ElectricUpdateMessageQueueQueryDTO();
        queryDTO.setElectricCoreCode(subTaskEntity.getElectricCoreCode());
        List<ElectricUpdateMessageQueueEntity> list = this.electricUpdateMessageQueueDao.queryList(queryDTO);
        if (list.size() == 0)
            this.interfaceManager.sendAddElectricCoreMessageToAI(subTaskEntity);
    }

    /**
     * 发送电芯更新编码消息
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendElectricCoreClearMessage(SubTaskEntity subTaskEntity) {
        ElectricUpdateMessageQueueQueryDTO queryDTO = new ElectricUpdateMessageQueueQueryDTO();
        queryDTO.setElectricCoreCode(subTaskEntity.getElectricCoreCode());
        List<ElectricUpdateMessageQueueEntity> list = this.electricUpdateMessageQueueDao.queryList(queryDTO);
        for (ElectricUpdateMessageQueueEntity entity : list) {
            this.interfaceManager.sendClearElectricCoreMessageToAI(subTaskEntity, entity);
        }
    }



    /**
     * 发送极组消息到AI系统
     * @param isChange
     * @return
     */
    public ResponseDTO<InterfaceLogEntity> sendPoleGroupMessageToAI(Long mainTaskId,
                                                                   Long subTaskId,
                                                                   String electricCoreCode,
                                                                   String poleGroupNumber,
                                                                   InterfaceModuleEnum interfaceModuleEnum,
                                                                   Integer isChange) {
        String currentDateTime = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);

        Map<String, Object> param = new HashMap<>();
        param.put("isChange", isChange);
        param.put("sgroupNumber", poleGroupNumber);
        param.put("createTime", currentDateTime);
        InterfaceLogEntity interfaceLogEntity = new InterfaceLogEntity();
        interfaceLogEntity.setSubTaskId(subTaskId);
        interfaceLogEntity.setMainTaskId(mainTaskId);
        interfaceLogEntity.setElectricCoreCode(electricCoreCode);
        interfaceLogEntity.setPoleGroupNumber(poleGroupNumber);
        interfaceLogEntity.setModule(interfaceModuleEnum.getValue());
        interfaceLogEntity.setContent(interfaceModuleEnum.getDesc());
        interfaceLogEntity.setParam(param);
        interfaceLogEntity.setCreateTime(new Date());
        if (Objects.nonNull(RequestTokenUtil.getThreadLocalUser())) {
            interfaceLogEntity.setCreateBy(RequestTokenUtil.getThreadLocalUser().getRequestUserId());
        }
        interfaceLogEntity.setRevision(CommonConst.DEFAULT_OPTI_LOCK_REVISION);

        try {
            String msgBody = JSON.toJSONString(param);
            log.info("Send pole group message to AI System >>> {}", msgBody);
            String responseStr = HttpUtil.post(this.aiInterfaceJzUrl, msgBody, 1000 * 30);
            log.info("Pole group message returned by AI System >>> {}", responseStr);
            RetDTO retDTO = JSON.parseObject(responseStr, RetDTO.class);
            if (JudgeEnum.YES.getValue().equals(retDTO.getIsSuccess())) {
                interfaceLogEntity.setResult(JudgeEnum.YES.getValue());
            } else {
                interfaceLogEntity.setResult(JudgeEnum.NO.getValue());
                interfaceLogEntity.setFailReason(retDTO.getMsg());
            }
            interfaceLogEntity.setStatus(JudgeEnum.YES.getValue().toString());
            interfaceLogEntity.setCompletionTime(new Date());
            this.interfaceLogDao.insert(interfaceLogEntity);

            return ResponseDTO.succData(interfaceLogEntity);
        } catch (Exception ex) {
            log.error("Send pole group message to AI error", ex);

            interfaceLogEntity.setResult(JudgeEnum.NO.getValue());
            interfaceLogEntity.setFailReason(ex.getMessage());
            interfaceLogEntity.setStatus(JudgeEnum.YES.getValue().toString());
            interfaceLogEntity.setCompletionTime(new Date());
            this.interfaceLogDao.insert(interfaceLogEntity);

            return ResponseDTO.wrap(TaskResponseCodeConst.AI_INVOKE_FAIL);
        }
    }

    public void startScanAIImageTask(InterfaceLogEntity scanImageLogEntity) {
        String cronExpression = DEFAULT_CRON_EXPRESSION;
        SystemConfigDTO systemConfigDTO = this.systemConfigService.getCacheByKey(SystemConfigEnum.Key.AI_INTERFACE_POLL_CRON);
        if (Objects.nonNull(systemConfigDTO)) {
            cronExpression = systemConfigDTO.getConfigValue();
        }
        if (Objects.nonNull(scanImageLogEntity) && Objects.nonNull(scanImageLogEntity.getId())) {
            if (!this.dyTaskService.taskIsRunning(scanImageLogEntity.getId()))
                this.dyTaskService.scheduleTask(scanImageLogEntity.getId(), new AIImageDyTask(scanImageLogEntity), cronExpression);
        }
    }
}
